
package com.cmc.dao.hibernate;

import java.util.List;

import com.cmc.dao.hibernate.BaseDaoHibernate;
import com.cmc.model.WorkType;
import com.cmc.dao.WorkTypeDao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;

public class WorkTypeDaoHibernate extends BaseDaoHibernate implements WorkTypeDao {

    /**
     * @see com.cmc.dao.WorkTypeDao#getWorkTypes(com.cmc.model.WorkType)
     */
    public List getWorkTypes(final WorkType workType) {
        //return getHibernateTemplate().find("from WorkType");

        /* Remove the line above and uncomment this code block if you want 
           to use Hibernate's Query by Example API. */
        if (workType == null) {
            return getHibernateTemplate().find("from WorkType");
        } else {
            // filter on properties set in the workType
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Example ex = Example.create(workType).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    return session.createCriteria(WorkType.class).add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }
    }

    /**
     * @see com.cmc.dao.WorkTypeDao#getWorkType(Long id)
     */
    public WorkType getWorkType(final Long id) {
        WorkType workType = (WorkType) getHibernateTemplate().get(WorkType.class, id);
        if (workType == null) {
            log.warn("uh oh, workType with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(WorkType.class, id);
        }

        return workType;
    }

    /**
     * @see com.cmc.dao.WorkTypeDao#saveWorkType(WorkType workType)
     */    
    public void saveWorkType(final WorkType workType) {
        getHibernateTemplate().saveOrUpdate(workType);
    }

    /**
     * @see com.cmc.dao.WorkTypeDao#removeWorkType(Long id)
     */
    public void removeWorkType(final Long id) {
        getHibernateTemplate().delete(getWorkType(id));
    }
}
